<template>
  <div class="resource-pool-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="left-actions">
            <el-checkbox v-model="selectAll" @change="toggleSelectAll">已选中 {{ selectedRowKeys.length }} 项</el-checkbox>
            <el-button size="small" @click="handleDelete">删除客户</el-button>      
            <el-button size="small" @click="handleAddToFollow">添加跟进客户</el-button>
            <el-button size="small" @click="openCreateTaskDialog">轮呼</el-button>

            <el-button size="small" @click="handleAssign">分配客户</el-button>
            <el-button size="small" @click="handleRecycle">回收到公海</el-button>
            <el-button size="small" @click="handleMove">资源库转移</el-button>
            <el-button size="small" @click="handleBatchSendSms">批量发短信</el-button>
          </div>
          <div class="right-actions">
            <el-button type="primary" size="small" @click="handleCreate">新建</el-button>
            <el-dropdown>
              <el-button size="small">导入</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleImport('file')">导入文件</el-dropdown-item>
                  <el-dropdown-item @click="handleImport('excel')">导入Excel</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-dropdown>
              <el-button size="small">导入记录</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleImportHistory">查看导入记录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </template>

      <!-- 筛选/搜索区域 -->
      <div class="filter-bar">
        <el-select v-model="searchType" placeholder="搜索类型" style="width: 100px; margin-right: 8px">
          <el-option label="客户姓名" value="customer_name" />
          <el-option label="手机号" value="phone" />
          <el-option label="城市" value="city" />
          <el-option label="来源" value="source" />
        </el-select>
        <el-input v-model="searchValue" :placeholder="`请输入${getSearchTypePlaceholder(searchType.value)}`" :prefix-icon="Search" clearable style="width: 240px" @keyup.enter="fetchList" />
        <el-select v-model="advancedFilter" placeholder="高级筛选" clearable style="width: 140px">
          <el-option label="潜在客户" value="潜在客户" />
          <el-option label="意向客户" value="意向客户" />
          <el-option label="需求客户" value="需求客户" />
        </el-select>
        <el-date-picker v-model="dateRange" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 260px" />
        <el-button type="primary" :icon="Search" @click="fetchList">筛选</el-button>
        <el-button @click="resetFilters">重置</el-button>
      </div>

      <!-- 数据表格 -->
      <el-table
        ref="tableRef"
        :data="tableData"
        style="width: 100%"
        border
        stripe
        :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 600 }"
        :row-style="{ height: '60px' }"
        :cell-style="{ padding: '12px 0' }"
        @selection-change="onSelectionChange"
      >
        <el-table-column type="selection" width="48" />
        <el-table-column prop="customer_name" label="姓名" min-width="160">
          <template #default="{ row }">
            <div class="name-cell">
              <el-avatar :size="28" :src="row.avatar" style="margin-right: 8px" />
              <div class="name-text">{{ row.customer_name }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="140">
          <template #default="{ row }">
            <span>{{ row.phone || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="{ row }">
            <span>{{ row.gender || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="客户类型" width="110">
          <template #default="{ row }">
            <el-tag size="small" :type="mapTypeToTag(row.type).type">{{ mapTypeToTag(row.type).text }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="assistStage" label="助贷阶段" width="120" />
        <el-table-column prop="customer_level" label="AI意向等级" width="120" />
        <el-table-column prop="expected_amount" label="期望金额" width="120" />
        <el-table-column prop="customer_situation" label="客户情况" min-width="200" show-overflow-tooltip />
        <el-table-column prop="source" label="信息来源" width="160" />
        <el-table-column prop="salesman_id" label="营销专员" width="140" />
        <el-table-column prop="tags" label="客户标签" min-width="160">
          <template #default="{ row }">
            <div class="tags-cell">
              <el-tag v-for="t in parseTags(row.tags)" :key="t" size="small" class="tag-item">{{ t }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="called_count" label="轮呼次数" width="120">
          <template #default="{ row }">
            <el-tag size="small">
              {{ row.called_count || 0 }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              text 
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button 
              type="success" 
              size="small" 
              text 
              @click="handleView(row)"
            >
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="page"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="onSizeChange"
          @current-change="onPageChange"
        />
      </div>
      
      <!-- 创建轮呼任务对话框 -->
      <el-dialog
        v-model="createTaskVisible"
        title="创建轮呼任务"
        width="520px"
      >
        <el-form :model="createForm" label-width="100px">
          <el-form-item label="任务名称" required>
            <el-input v-model="createForm.task_name" placeholder="请输入任务名称" />
          </el-form-item>
          <el-form-item label="任务通道" required>
            <el-input v-model="createForm.channel" placeholder="请输入任务通道" />
          </el-form-item>
          <el-form-item label="随机数量">
            <div style="display: flex; gap: 8px; align-items: center; flex-wrap: wrap;">
              <el-input-number
                v-model="createForm.random_count"
                :min="0"
                :max="100000"
                placeholder="可不填"
              />
              <div style="display:flex; gap:6px;">
                <el-tag @click="setPresetCount(30)" style="cursor:pointer;">30</el-tag>
                <el-tag @click="setPresetCount(50)" style="cursor:pointer;">50</el-tag>
                <el-tag @click="setPresetCount(100)" style="cursor:pointer;">100</el-tag>
                <el-tag @click="setPresetCount(200)" style="cursor:pointer;">200</el-tag>
                <el-tag type="info" @click="setPresetCount(undefined as any)" style="cursor:pointer;">不设置</el-tag>
              </div>
            </div>
            <div style="color:#909399; font-size:12px; margin-top:8px;">如已选择客户将优先使用所选客户；未选择时可通过随机数量创建。</div>
          </el-form-item>
          <el-form-item label="已选客户">
            <el-tag v-if="selectedRowKeys.length > 0" type="success">{{ selectedRowKeys.length }} 个</el-tag>
            <span v-else style="color:#909399">未选择</span>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="createTaskVisible = false">取消</el-button>
          <el-button type="primary" :loading="creatingTask" @click="submitCreateTask">创建</el-button>
        </template>
      </el-dialog>

      <!-- 文件上传对话框 -->
      <el-dialog
        v-model="uploadVisible"
        title="导入客户数据"
        width="400px"
        @close="closeUploadDialog"
      >
        <div class="upload-dialog-content">
          <p class="upload-tip">请选择要导入的文件（仅支持 {{ importType === 'file' ? 'CSV/Excel' : 'Excel' }} 格式）</p>
          
          <el-upload
            class="upload-btn"
            action=""
            :auto-upload="false"
            :limit="1"
            :on-change="(file) => handleFileUpload(file.raw as UploadRawFile)"
            :show-file-list="true"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                {{ importType === 'file' ? 'CSV文件或Excel文件' : 'Excel文件' }}，大小不超过10MB
              </div>
            </template>
          </el-upload>
          
          <!-- 上传进度条 -->
          <el-progress
            v-if="uploadProgress > 0 && uploadProgress < 100"
            :percentage="uploadProgress"
            status="success"
            style="margin-top: 16px"
          />
          <p v-if="uploadProgress > 0 && uploadProgress < 100" class="progress-text">
            正在上传... {{ uploadProgress }}%
          </p>
        </div>
      </el-dialog>
    </el-card>

    <!-- 客户详情抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      title="客户详情"
      direction="rtl"
      size="40%"
      :with-header="true"
      destroy-on-close
      class="customer-detail-drawer"
    >
      <div v-if="currentCustomer" class="customer-detail">
        <!-- 客户基本信息卡片 -->
        <div class="info-header">
          <h2 class="customer-name">{{ currentCustomer.customer_name }}</h2>
          <div class="customer-phone">{{ currentCustomer.phone || '-' }}</div>
        </div>
        
        <!-- 详细信息描述列表 -->
        <el-descriptions :column="1" border class="mt-4">
          <el-descriptions-item label="客户类型">{{ currentCustomer.type || '-' }}</el-descriptions-item>
          <el-descriptions-item label="助贷阶段">{{ currentCustomer.assistStage || '-' }}</el-descriptions-item>
          <el-descriptions-item label="AI意向等级">{{ currentCustomer.customer_level || '-' }}</el-descriptions-item>
          <el-descriptions-item label="期望金额">{{ currentCustomer.expected_amount || '-' }}</el-descriptions-item>
          <el-descriptions-item label="信息来源">{{ currentCustomer.source || '-' }}</el-descriptions-item>
          <el-descriptions-item label="营销专员">{{ currentCustomer.salesman_id || '-' }}</el-descriptions-item>
          <el-descriptions-item label="客户情况" :span="2">
            <div class="situation-content">{{ currentCustomer.customer_situation || '-' }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="客户标签">
            <el-tag v-for="t in parseTags(currentCustomer.tags)" :key="t" size="small" class="tag-item ml-2">{{ t }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="轮呼次数">{{ currentCustomer.called_count || 0 }}</el-descriptions-item>
        </el-descriptions>
        
        <!-- 操作按钮区域 -->
        <div class="detail-actions">
          <el-button type="primary" @click="handleEditCustomer(currentCustomer)">
            编辑客户
          </el-button>
          <el-button type="success" @click="handleSendSingleSms(currentCustomer)">
            发送短信
          </el-button>
          <el-button type="warning" @click="handleCallCustomer(currentCustomer)">
            拨打电话
          </el-button>
          <el-button @click="handleAddFollow(currentCustomer)">
            添加跟进
          </el-button>
        </div>
      </div>
    </el-drawer>
    
    <!-- 编辑客户对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑客户信息"
      width="600px"
    >
      <el-form label-width="100px" size="default">
        <el-form-item label="客户姓名" required>
          <el-input v-model="editForm.customer_name" placeholder="请输入客户姓名" maxlength="20" />
        </el-form-item>
        
        <el-form-item label="手机号" required>
          <el-input v-model="editForm.phone" placeholder="请输入手机号" maxlength="11" />
        </el-form-item>
        
        <el-form-item label="客户类型">
          <el-select v-model="editForm.type" placeholder="请选择客户类型">
            <el-option v-for="type in customerTypes" :key="type.value" :label="type.label" :value="type.value" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="助贷阶段">
          <el-input v-model="editForm.assistStage" placeholder="请输入助贷阶段" />
        </el-form-item>
        
        <el-form-item label="AI意向等级">
          <el-input v-model="editForm.customer_level" placeholder="请输入AI意向等级" />
        </el-form-item>
        
        <el-form-item label="期望金额">
          <el-input v-model="editForm.expected_amount" placeholder="请输入期望金额" />
        </el-form-item>
        
        <el-form-item label="信息来源">
          <el-input v-model="editForm.source" placeholder="请输入信息来源" />
        </el-form-item>
        
        <el-form-item label="营销专员">
          <el-input v-model="editForm.salesman_id" placeholder="请输入营销专员" />
        </el-form-item>
        
        <el-form-item label="客户情况">
          <el-input v-model="editForm.customer_situation" type="textarea" rows="4" placeholder="请输入客户情况" />
        </el-form-item>
        
        <el-form-item label="客户标签">
          <div class="tag-input-container">
            <el-tag 
              v-for="tag in editForm.tags" 
              :key="tag" 
              closable 
              @close="removeTag(tag)"
              class="tag-item"
            >
              {{ tag }}
            </el-tag>
            <el-input
              v-model="tagInput"
              class="tag-input"
              placeholder="输入标签后按Enter添加"
              @keyup.enter="handleTagInput"
              size="small"
              maxlength="10"
            />
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveCustomer">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElTag, ElButton, ElDialog, ElDrawer, ElDescriptions, ElDescriptionsItem } from 'element-plus'
import { Search, Edit, Message, Phone, Star } from '@element-plus/icons-vue'
import axios from 'axios'
import { userInfo, isLoggedIn } from '@/utils/userStore'

const router = useRouter()
const tableRef = ref()
const searchType = ref('customer_name') // 默认按客户姓名搜索
const searchValue = ref('') // 搜索值
const advancedFilter = ref('')
const dateRange = ref<[Date, Date] | null>(null)

const page = ref(1)
const pageSize = ref(10)
const total = ref(0)

const tableData = ref<any[]>([])
const selectedRowKeys = ref<string[]>([])
const selectAll = ref(false)

// 将客户类型数字转换为文本
const mapTypeToTag = (type: number) => {
  switch (type) {
    case 1:
      return { type: 'success', text: '潜在客户' }
    case 2:
      return { type: 'warning', text: '意向客户' }
    case 3:
      return { type: 'info', text: '需求客户' }
    case 4:
      return { type: 'primary', text: '签单客户' }
    case 5:
      return { type: 'danger', text: '放款客户' }
    default:
      return { type: 'info', text: '未知类型' }
  }
}


// 解析标签字符串为数组
const parseTags = (tags: string) => {
  if (!tags) return []
  try {
    return JSON.parse(tags)
  } catch {
    return tags.split(',').filter(t => t.trim())
  }
}

// 根据搜索类型获取占位符文本
const getSearchTypePlaceholder = (type: string) => {
  const placeholders: Record<string, string> = {
    customer_name: '客户姓名',
    phone: '手机号',
    city: '城市',
    source: '来源'
  }
  return placeholders[type] || '搜索内容'
}

const fetchList = async () => {
  try {
    // 构建查询参数
    const params: any = {
      page: page.value,
      page_size: pageSize.value
    }
    
    // 根据选择的搜索类型设置对应的参数
    if (searchValue.value) {
      params[searchType.value] = searchValue.value
    }
    
    // 添加高级筛选条件
    if (advancedFilter.value) {
      params.type = {
        '潜在客户': 1,
        '意向客户': 2,
        '需求客户': 3
      }[advancedFilter.value]
    }
    
    // 添加日期范围筛选
    if (dateRange.value && dateRange.value.length === 2) {
      params.start_date = dateRange.value[0].toISOString().split('T')[0] // 开始日期
      params.end_date = dateRange.value[1].toISOString().split('T')[0] // 结束日期
    }
    
    // 发送请求到后端接口
    const response = await axios.get('/customers/list', { params })
    

    if (response.data.data && Array.isArray(response.data.data.customers)) {
      tableData.value = response.data.data.customers
      // 尝试多种可能的total值位置，确保分页功能正常
      total.value = response.data.total || response.data.data.total || tableData.value.length
    } else {
      // 兜底处理，确保tableData始终是数组
      console.warn('API响应数据结构不符合预期', response.data)
      tableData.value = []
      total.value = 0
    }
    
    console.log('获取客户列表成功，共', total.value, '条数据')
  } catch (error: any) {
    console.error('获取客户列表失败:', error)
    // 区分网络错误和服务器错误
    if (error.response) {
      // 服务器返回错误
      const errorMsg = error.response.data?.message || `获取客户列表失败: ${error.response.status}`
      ElMessage.error(errorMsg)
    } else if (error.request) {
      // 请求发出但无响应
      ElMessage.error('网络连接失败，请检查网络')
    } else {
      // 其他错误
      ElMessage.error('获取客户列表失败，请稍后重试')
    }
    tableData.value = []
    total.value = 0
  }
}

const resetFilters = () => {
  searchType.value = 'customer_name' // 重置为默认搜索类型
  searchValue.value = '' // 清空搜索值
  advancedFilter.value = ''
  dateRange.value = null
  page.value = 1
  fetchList()
}

const onPageChange = (p: number) => {
  page.value = p
  fetchList()
}

const onSizeChange = (s: number) => {
  pageSize.value = s
  page.value = 1
  fetchList()
}

const onSelectionChange = (rows: any[]) => {
  selectedRowKeys.value = rows.map(r => r.customer_id)
  selectAll.value = selectedRowKeys.value.length === tableData.value.length && tableData.value.length > 0
}

const toggleSelectAll = () => {
  if (!tableRef.value) return
  if (selectAll.value) {
    tableRef.value.clearSelection()
    tableData.value.forEach((row: any) => tableRef.value.toggleRowSelection(row, true))
    // 确保selectedRowKeys使用customer_id
    selectedRowKeys.value = tableData.value.map(r => r.customer_id)
  } else {
    tableRef.value.clearSelection()
    selectedRowKeys.value = []
  }
}





// 创建轮呼任务对话框逻辑
const createTaskVisible = ref(false)
const creatingTask = ref(false)
const createForm = ref<{ task_name: string; channel: string; random_count?: number | null }>(
  { task_name: '', channel: '', random_count: null }
)

const openCreateTaskDialog = () => {
  // 允许未选择客户也能创建（依赖随机数量）
  createTaskVisible.value = true
}

const setPresetCount = (count?: number) => {
  if (typeof count === 'number') {
    createForm.value.random_count = count
  } else {
    createForm.value.random_count = null
  }
}

const submitCreateTask = async () => {
  if (!createForm.value.task_name || !createForm.value.channel) {
    ElMessage.warning('请填写任务名称和任务通道')
    return
  }

  // 组装请求参数
  const payload: any = {
    task_name: createForm.value.task_name,
    created_by: (userInfo && (userInfo as any).username) || localStorage.getItem('username') || 'unknown_user',
    channel: createForm.value.channel
  }

  if (selectedRowKeys.value.length > 0) {
    payload.customer_ids = selectedRowKeys.value
  } else if (createForm.value.random_count && createForm.value.random_count > 0) {
    payload.random_count = createForm.value.random_count
  } else {
    ElMessage.warning('未选择客户时需设置随机数量')
    return
  }

  creatingTask.value = true
  try {
    const resp = await axios.post('/call/tasks/create', payload)
    if (resp.data && (resp.data.code === 200 || resp.status === 200)) {
      const resData = resp.data.data || resp.data
      ElMessage.success(resData.message || '创建轮呼任务成功')
      createTaskVisible.value = false
      // 清空选择，便于下一次操作
      selectedRowKeys.value = []
      selectAll.value = false
      if (tableRef.value) tableRef.value.clearSelection()
      // 重置表单
      createForm.value = { task_name: '', channel: '', random_count: null }
    } else {
      ElMessage.error(resp.data?.message || '创建轮呼任务失败')
    }
  } catch (e:any) {
    ElMessage.error(e?.response?.data?.message || '创建轮呼任务失败，请稍后重试')
  } finally {
    creatingTask.value = false
  }
}

const handleCreate = () => {
  ElMessage.info('新建客户功能待实现')
}

// 导入相关功能定义
import { ref, onMounted } from 'vue'
import { ElUpload, UploadRawFile, ElMessageBox, ElMessage } from 'element-plus'
import { Search, Edit, Message, Phone, Star } from '@element-plus/icons-vue'
import type { AxiosProgressEvent } from 'axios'

// 导入相关的响应式状态
const uploadProgress = ref(0)
const uploadVisible = ref(false)
const importType = ref('')

// 标签输入状态
const tagInput = ref('')

// 处理标签输入
const handleTagInput = () => {
  if (tagInput.value.trim()) {
    addTag(tagInput.value.trim())
    tagInput.value = ''
  }
}

// 处理导入功能
const handleImport = (type: string) => {
  importType.value = type
  uploadVisible.value = true
}

// 处理文件上传
const handleFileUpload = async (file: UploadRawFile) => {
  try {
    // 重置进度
    uploadProgress.value = 0
    
    // 创建FormData对象
    const formData = new FormData()
    formData.append('file', file)
    formData.append('import_type', importType.value)
    
    // 显示上传中消息
    ElMessage({ message: '文件上传中，请稍候...', type: 'info' })
    
    // 调用导入接口
    const response = await axios.post('/customers/import', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
      timeout: 80000,
      onUploadProgress: (event: AxiosProgressEvent) => {
        if (event.total) {
          uploadProgress.value = Math.round((event.loaded / event.total) * 100)
        }
      }

    })
    
    // 处理成功响应
    if (response.data && response.data.code === 200) {
      ElMessage.success('客户数据导入成功！')
      // 重新加载列表以显示新导入的数据
      fetchList()
    } else {
      ElMessage.error(response.data?.message || '导入失败，请重试')
    }
  } catch (error: any) {
    console.error('导入失败:', error)
    // 区分网络错误和服务器错误
    if (error.response) {
      // 服务器返回错误
      const errorMsg = error.response.data?.message || `导入失败: ${error.response.status}`
      ElMessage.error(errorMsg)
    } else if (error.request) {
      // 请求发出但无响应
      ElMessage.error('网络连接失败，请检查网络')
    } else {
      // 其他错误
      ElMessage.error('导入失败，请稍后重试')
    }
  } finally {
    // 重置并关闭上传对话框
    uploadProgress.value = 0
    uploadVisible.value = false
  }
  
  // 阻止默认上传行为
  return false
}

// 关闭上传对话框
const closeUploadDialog = () => {
  uploadVisible.value = false
  uploadProgress.value = 0
}

const handleImportHistory = () => {
  ElMessage.info('查看导入记录功能待实现')
}

const handleDelete = async () => {
  if (selectedRowKeys.value.length === 0) {
    ElMessage.warning('请先选择要删除的客户')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRowKeys.value.length} 个客户吗？此操作不可撤销。`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    // 调用删除接口
    const response = await axios.post('/customers/batch-delete', {
      customer_ids: selectedRowKeys.value
    })
    
    if (response.data && response.data.code === 200) {
      ElMessage.success(`成功删除 ${selectedRowKeys.value.length} 个客户`)
      fetchList() // 重新获取列表
      selectedRowKeys.value = [] // 清空选择
      selectAll.value = false
    } else {
      ElMessage.error('删除失败：' + (response.data?.message || '未知错误'))
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除操作失败')
    }
  }
}

const handleAssign = () => {
  if (selectedRowKeys.value.length === 0) {
    ElMessage.warning('请先选择要分配的客户')
    return
  }
  ElMessage.info(`分配客户功能待实现，已选择 ${selectedRowKeys.value.length} 个客户`)
}

const handleRecycle = () => {
  if (selectedRowKeys.value.length === 0) {
    ElMessage.warning('请先选择要回收的客户')
    return
  }
  ElMessageBox.confirm('确定要将选中的客户回收到公海吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success(`已回收 ${selectedRowKeys.value.length} 个客户到公海`)
    selectedRowKeys.value = []
    selectAll.value = false
    if (tableRef.value) {
      tableRef.value.clearSelection()
    }
  }).catch(() => {})
}

const handleMove = async () => {
  if (selectedRowKeys.value.length === 0) {
    ElMessage.warning('请先选择要转移的客户')
    return
  }

  ElMessageBox.confirm('确定要将选中的客户转移到其他资源库吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 这里应该调用转移资源库的接口
    try {
      const response = await axios.post('/customers/move', {
        customer_ids: selectedRowKeys.value
      })
      if (response.data.code === 200) {
        ElMessage.success('资源库转移成功')
        fetchList()
        selectedRowKeys.value = []
        selectAll.value = false
        if (tableRef.value) {
          tableRef.value.clearSelection()
        }
      } else {
        ElMessage.error(response.data.message || '资源库转移失败')
      }
    } catch (error) {
      ElMessage.error('资源库转移失败，请稍后重试')
      console.error('资源库转移失败:', error)
    }
  }).catch(() => {})
}

// 批量发送短信功能
const handleBatchSendSms = async () => {
  if (selectedRowKeys.value.length === 0) {
    ElMessage.warning('请选择需要发送短信的客户')
    return
  }

  // 过滤出有手机号的客户
  const customersWithPhone = tableData.value.filter(row => 
    selectedRowKeys.value.includes(row.customer_id) && row.phone
  )
  if (customersWithPhone.length === 0) {
    ElMessage.warning('所选客户中没有有效的手机号')
    return
  }

  // 收集所有手机号，用逗号隔开
  const mobileNumbers = customersWithPhone.map(row => row.phone).join(',')

  // 弹出确认对话框
  ElMessageBox.confirm(`确定要向选中的 ${customersWithPhone.length} 个客户发送短信吗？`, '确认发送', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
        // 调用发送短信接口
        const response = await axios.post('/sms/send', {
          mobile: mobileNumbers
        })
      
      if (response.data.code == 200) {
        ElMessage.success(`短信发送成功，共发送${customersWithPhone.length}条`)
      } else {
        ElMessage.error(response.data.message || '短信发送失败')
      }
    } catch (error) {
      ElMessage.error('短信发送失败，请稍后重试')
      console.error('短信发送失败:', error)
    }
  }).catch(() => {})
}

// 添加到跟进客户
const handleAddToFollow = () => {
  if (selectedRowKeys.value.length === 0) {
    ElMessage.warning('请先选择要添加到跟进的客户')
    return
  }
  
  // 获取选中的客户数据
  const selectedCustomers = tableData.value.filter(row => 
    selectedRowKeys.value.includes(row.customer_id)
  )
  
  ElMessageBox.confirm(`确定要将选中的 ${selectedCustomers.length} 个客户添加到跟进客户吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 调用后端API将客户添加到跟进客户
      const response = await axios.post('/customers/batch-update-following', {
        customer_ids: selectedRowKeys.value
      })
      
      // 处理成功响应
      if (response.data && response.data.code === 200) {
        ElMessage.success(`已成功将 ${selectedCustomers.length} 个客户添加到跟进客户`)
        
        // 刷新列表以更新客户状态
        fetchList()
      } else {
        ElMessage.error(response.data?.msg || response.data?.message || '添加失败，请重试')
      }
      
      // 清空选择
      selectedRowKeys.value = []
      selectAll.value = false
      if (tableRef.value) {
        tableRef.value.clearSelection()
      }
    } catch (error: any) {
      console.error('添加到跟进客户失败:', error)
      // 区分网络错误和服务器错误
      if (error.response) {
        // 服务器返回错误，优先显示服务端返回的msg
        const errorMsg = error.response.data?.msg || error.response.data?.message || `添加失败: ${error.response.status}`
        ElMessage.error(errorMsg)
      } else if (error.request) {
        // 请求发出但无响应
        ElMessage.error('网络连接失败，请检查网络')
      } else {
        // 其他错误
        ElMessage.error('添加失败，请稍后重试')
      }
    }
  }).catch(() => {})
}

// 编辑客户
const handleEdit = (row: any) => {
  handleEditCustomer(row)
}

// 查看客户详情相关状态
const drawerVisible = ref(false)
const currentCustomer = ref(null)

// 编辑客户相关状态
const editDialogVisible = ref(false)
const editForm = ref({
  customer_name: '',
  phone: '',
  type: '',
  assistStage: '',
  customer_level: '',
  expected_amount: '',
  customer_situation: '',
  source: '',
  salesman_id: '',
  tags: []
})

// 客户类型选项
const customerTypes = [
  { value: 1, label: '潜在客户' },
  { value: 2, label: '意向客户' },
  { value: 3, label: '需求客户' },
  { value: 4, label: '签单客户' },
  { value: 5, label: '放款客户' }
]

// 查看客户详情
const handleView = (row: any) => {
  // 添加空值检查
  if (!row) {
    ElMessage.warning('客户数据无效')
    return
  }
  
  // 创建新对象以避免响应式问题
  currentCustomer.value = { ...row }
  drawerVisible.value = true
}

// 打开编辑对话框
const handleEditCustomer = (customer: any) => {
  // 添加空值检查
  if (!customer) {
    ElMessage.warning('客户数据无效')
    return
  }
  
  // 关闭详情抽屉
  drawerVisible.value = false
  
  // 填充编辑表单数据
  editForm.value = {
    customer_name: customer.customer_name || '',
    phone: customer.phone || '',
    type: customer.type || '',
    assistStage: customer.assistStage || '',
    customer_level: customer.customer_level || '',
    expected_amount: customer.expected_amount || '',
    customer_situation: customer.customer_situation || '',
    source: customer.source || '',
    salesman_id: customer.salesman_id || '',
    tags: parseTags(customer.tags) || []
  }
  
  // 设置当前编辑的客户ID，创建一个新对象以避免响应式问题
  currentCustomer.value = { ...customer }
  
  // 显示编辑对话框
  editDialogVisible.value = true
}

// 保存编辑的客户信息
const saveCustomer = async () => {
  try {
    // 验证表单数据
    if (!editForm.value.customer_name) {
      ElMessage.warning('请输入客户姓名')
      return
    }
    
    if (!editForm.value.phone) {
      ElMessage.warning('请输入客户手机号')
      return
    }
    
    // 构建更新数据
    const updateData: any = {
      ...editForm.value,
      customer_id: currentCustomer.value.customer_id,
      tags: JSON.stringify(editForm.value.tags)
    }
    
    // 如果expected_amount为空，则不传递该字段
    if (!updateData.expected_amount || updateData.expected_amount.trim() === '') {
      delete updateData.expected_amount
    }
    
    // 调用后端更新接口
    const response = await axios.post('/customers/update', updateData)
    
    if (response.data && response.data.code === 200) {
      ElMessage.success('客户信息更新成功')
      
      // 关闭编辑对话框
      editDialogVisible.value = false
      
      // 重新获取客户列表
      fetchList()
    } else {
      ElMessage.error(response.data?.msg || response.data?.message || '更新失败，请重试')
    }
  } catch (error: any) {
    console.error('更新客户信息失败:', error)
    // 区分网络错误和服务器错误
    if (error.response) {
      // 服务器返回错误，优先显示服务端返回的msg
      const errorMsg = error.response.data?.msg || error.response.data?.message || `更新失败: ${error.response.status}`
      ElMessage.error(errorMsg)
    } else if (error.request) {
      // 请求发出但无响应
      ElMessage.error('网络连接失败，请检查网络')
    } else {
      // 其他错误
      ElMessage.error('更新失败，请稍后重试')
    }
  }
}

// 添加标签
const addTag = (tag: string) => {
  if (!tag || editForm.value.tags.includes(tag)) return
  editForm.value.tags.push(tag)
}

// 删除标签
const removeTag = (tag: string) => {
  const index = editForm.value.tags.indexOf(tag)
  if (index !== -1) {
    editForm.value.tags.splice(index, 1)
  }
}

// 发送单个短信
const handleSendSingleSms = (customer: any) => {
  if (!customer.phone) {
    ElMessage.warning('该客户没有手机号，无法发送短信')
    return
  }
  
  ElMessageBox.confirm(`确定要向 ${customer.customer_name} (${customer.phone}) 发送短信吗？`, '确认发送', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await axios.post('/sms/send', {
        mobile: customer.phone
      })
      
      if (response.data.code == 200) {
        ElMessage.success('短信发送成功')
      } else {
        ElMessage.error(response.data.message || '短信发送失败')
      }
    } catch (error) {
      ElMessage.error('短信发送失败，请稍后重试')
      console.error('短信发送失败:', error)
    }
  }).catch(() => {})
}

// 拨打电话
const handleCallCustomer = (customer: any) => {
  if (!customer.phone) {
    ElMessage.warning('该客户没有手机号，无法拨打电话')
    return
  }
  
  // 生成姓名拼音（完整拼音）
  const getPinyin = (name: string): string => {
    if (!name) return ''
    
    // 汉字到完整拼音映射（扩展版本，包含更多常见汉字）
    const pinyinMap: { [key: string]: string } = {
      // 常见姓氏
      '张': 'zhang', '王': 'wang', '李': 'li', '赵': 'zhao', '刘': 'liu', '陈': 'chen', '杨': 'yang',
      '黄': 'huang', '周': 'zhou', '吴': 'wu', '徐': 'xu', '孙': 'sun', '马': 'ma', '朱': 'zhu',
      '胡': 'hu', '郭': 'guo', '何': 'he', '林': 'lin', '罗': 'luo', '梁': 'liang', '宋': 'song',
      '郑': 'zheng', '谢': 'xie', '韩': 'han', '唐': 'tang', '冯': 'feng', '于': 'yu', '董': 'dong',
      '萧': 'xiao', '程': 'cheng', '曹': 'cao', '袁': 'yuan', '邓': 'deng', '许': 'xu', '傅': 'fu',
      '沈': 'shen', '曾': 'zeng', '彭': 'peng', '吕': 'lv', '苏': 'su', '卢': 'lu', '蒋': 'jiang',
      '蔡': 'cai', '贾': 'jia', '丁': 'ding', '魏': 'wei', '薛': 'xue', '叶': 'ye', '阎': 'yan',
      '余': 'yu', '潘': 'pan', '杜': 'du', '戴': 'dai', '夏': 'xia', '钟': 'zhong', '汪': 'wang',
      '田': 'tian', '任': 'ren', '姜': 'jiang', '范': 'fan', '方': 'fang', '石': 'shi', '姚': 'yao',
      '谭': 'tan', '廖': 'liao', '邹': 'zou', '熊': 'xiong', '金': 'jin', '陆': 'lu', '郝': 'hao',
      '孔': 'kong', '白': 'bai', '崔': 'cui', '康': 'kang', '毛': 'mao', '邱': 'qiu', '秦': 'qin',
      '江': 'jiang', '史': 'shi', '顾': 'gu', '侯': 'hou', '邵': 'shao', '孟': 'meng', '龙': 'long',
      '万': 'wan', '段': 'duan', '雷': 'lei', '钱': 'qian', '汤': 'tang', '尹': 'yin', '黎': 'li',
      '易': 'yi', '常': 'chang', '武': 'wu', '乔': 'qiao', '贺': 'he', '赖': 'lai', '龚': 'gong',
      
      // 常见名字用字
      '伟': 'wei', '芳': 'fang', '娜': 'na', '秀英': 'xiuying', '敏': 'min', '静': 'jing', '丽': 'li',
      '强': 'qiang', '磊': 'lei', '军': 'jun', '洋': 'yang', '勇': 'yong', '艳': 'yan', '杰': 'jie',
      '娟': 'juan', '涛': 'tao', '明': 'ming', '超': 'chao', '秀兰': 'xiulan', '霞': 'xia', '平': 'ping',
      '刚': 'gang', '桂英': 'guiying', '小': 'xiao', '大': 'da', '文': 'wen', '华': 'hua', '金': 'jin',
      '健': 'jian', '国': 'guo', '宇': 'yu', '慧': 'hui', '巧': 'qiao', '美': 'mei', '玲': 'ling',
      '红': 'hong', '志': 'zhi', '建': 'jian', '晓': 'xiao', '晨': 'chen', '阳': 'yang', '春': 'chun',
      '雪': 'xue', '波': 'bo', '东': 'dong', '瑞': 'rui', '鹏': 'peng', '飞': 'fei', '丹': 'dan',
      '婷': 'ting', '婷婷': 'tingting', '小丽': 'xiaoli', '小明': 'xiaoming', '小红': 'xiaohong',
      '小华': 'xiaohua', '小军': 'xiaojun', '小强': 'xiaoqiang', '小波': 'xiaobo', '小飞': 'xiaofei',
      '小娟': 'xiaojuan', '小芳': 'xiaofang', '小燕': 'xiaoyan', '小梅': 'xiaomei', '小兰': 'xiaolan',
      '小萍': 'xiaoping', '小琴': 'xiaoqin', '小菊': 'xiaoju', '小英': 'xiaoying', '小慧': 'xiaohui',
      '小玲': 'xiaoling', '小静': 'xiaojing', '小勇': 'xiaoyong', '小刚': 'xiaogang', '小磊': 'xiaolei',
      '小涛': 'xiaotao', '小超': 'xiaochao', '小明': 'xiaoming', '小杰': 'xiaojie', '小鹏': 'xiaopeng',
      '小宇': 'xiaoyu', '小浩': 'xiaohao', '小晨': 'xiaochen', '小阳': 'xiaoyang', '小辉': 'xiaohui',
      '小波': 'xiaobo', '小飞': 'xiaofei', '小龙': 'xiaolong', '小虎': 'xiaohu', '小豹': 'xiaobao',
      '小狼': 'xiaolang', '小马': 'xiaoma', '小牛': 'xiaoniu', '小羊': 'xiaoyang', '小猴': 'xiaohou',
      '小鸡': 'xiaoji', '小狗': 'xiaogou', '小猪': 'xiaozhu', '小猫': 'xiaomao', '小兔': 'xiaotuzi',
      
      // 更多常见名字用字
      '玉': 'yu', '俊': 'jun', '浩': 'hao', '宇': 'yu', '轩': 'xuan', '睿': 'rui', '晨': 'chen',
      '博': 'bo', '涵': 'han', '子': 'zi', '梓': 'zi', '沫': 'mo', '然': 'ran', '佳': 'jia',
      '欣': 'xin', '怡': 'yi', '嘉': 'jia', '雨': 'yu', '桐': 'tong', '欣': 'xin', '妍': 'yan',
      '晨': 'chen', '宇': 'yu', '泽': 'ze', '昊': 'hao', '霖': 'lin', '铭': 'ming', '骏': 'jun',
      '彦': 'yan', '宸': 'chen', '凡': 'fan', '熙': 'xi', '坤': 'kun', '峰': 'feng', '磊': 'lei',
      '强': 'qiang', '帅': 'shuai', '勇': 'yong', '毅': 'yi', '杰': 'jie', '雄': 'xiong', '飞': 'fei',
      '鹏': 'peng', '涛': 'tao', '超': 'chao', '波': 'bo', '辉': 'hui', '亮': 'liang', '明': 'ming',
      '丽': 'li', '美': 'mei', '艳': 'yan', '芳': 'fang', '慧': 'hui', '静': 'jing', '雅': 'ya',
      '琳': 'lin', '娜': 'na', '婷': 'ting', '雪': 'xue', '梅': 'mei', '兰': 'lan', '菊': 'ju',
      '萍': 'ping', '琴': 'qin', '英': 'ying', '燕': 'yan', '红': 'hong', '玲': 'ling', '凤': 'feng',
      '花': 'hua', '月': 'yue', '彩': 'cai', '云': 'yun', '霞': 'xia', '虹': 'hong', '露': 'lu',
      '霜': 'shuang', '冰': 'bing', '清': 'qing', '香': 'xiang', '春': 'chun', '夏': 'xia', '秋': 'qiu',
      '冬': 'dong', '松': 'song', '柏': 'bai', '杨': 'yang', '柳': 'liu', '桃': 'tao', '荷': 'he',
      '竹': 'zhu', '梅': 'mei', '兰': 'lan', '菊': 'ju', '桂': 'gui', '芝': 'zhi', '萍': 'ping',
      
      // 数字和常用字
      '一': 'yi', '二': 'er', '三': 'san', '四': 'si', '五': 'wu', '六': 'liu', '七': 'qi', '八': 'ba',
      '九': 'jiu', '十': 'shi', '百': 'bai', '千': 'qian', '万': 'wan', '亿': 'yi', '零': 'ling',
      '东': 'dong', '西': 'xi', '南': 'nan', '北': 'bei', '中': 'zhong', '上': 'shang', '下': 'xia',
      '左': 'zuo', '右': 'you', '前': 'qian', '后': 'hou', '内': 'nei', '外': 'wai', '天': 'tian',
      '地': 'di', '人': 'ren', '民': 'min', '国': 'guo', '家': 'jia', '山': 'shan', '水': 'shui',
      '风': 'feng', '雨': 'yu', '雷': 'lei', '电': 'dian', '火': 'huo', '木': 'mu', '金': 'jin',
      '土': 'tu', '日': 'ri', '月': 'yue', '星': 'xing', '光': 'guang', '明': 'ming', '亮': 'liang'
    }
    
    let result = ''
    for (let i = 0; i < name.length; i++) {
      const char = name[i]
      result += pinyinMap[char] || char
    }
    return result
  }
  
  // 生成任务名称：姓名拼音_时间戳
  const pinyinName = getPinyin(customer.customer_name)
  const timestamp = Date.now()
  const taskName = `${pinyinName}_${timestamp}`
  
  // 创建轮呼任务
  createTaskForCustomer(customer, taskName)
}

// 为单个客户创建轮呼任务
const createTaskForCustomer = async (customer: any, taskName: string) => {
  try {
    const payload = {
      task_name: taskName,
      created_by: (userInfo && (userInfo as any).username) || localStorage.getItem('username') || 'unknown_user',
      channel: customer.phone,
      customer_ids: [customer.customer_id]
    }
    
    const resp = await axios.post('/call/tasks/create', payload)
    if (resp.data && (resp.data.code === 200 || resp.status === 200)) {
      const resData = resp.data.data || resp.data
      const taskId = resData.id || resData.task_id
      
      ElMessage.success(`已为 ${customer.customer_name} 创建轮呼任务：${taskName}`)
      
      // 自动开始轮呼任务
      if (taskId) {
        try {
          const startResp = await axios.post(`/call/tasks/${taskId}/start`)
          if (startResp.data && (startResp.data.code === 200 || startResp.status === 200)) {
            ElMessage.success(`轮呼任务已启动：${taskName}`)
          } else {
            ElMessage.warning(startResp.data?.msg || '任务创建成功，但启动失败，请手动启动')
          }
        } catch (startError: any) {
          console.error('启动轮呼任务失败:', startError)
          ElMessage.warning('任务创建成功，但启动失败，请手动启动')
        }
      }
    } else {
      ElMessage.error(resp.data?.message || '创建轮呼任务失败')
    }
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || '创建轮呼任务失败，请稍后重试')
    console.error('创建轮呼任务失败:', e)
  }
}

// 添加跟进
const handleAddFollow = (customer: any) => {
  ElMessageBox.confirm(`确定要将客户 ${customer.customer_name} 添加到跟进吗？`, '确认操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(async () => {
    try {
      const response = await axios.post('/customers/batch-update-following', {
        customer_ids: [customer.customer_id]
      })
      
      if (response.data && response.data.code === 200) {
        ElMessage.success('添加跟进成功')
      } else {
        ElMessage.error(response.data?.msg || response.data?.message || '添加跟进失败')
      }
    } catch (error: any) {
      console.error('添加跟进失败:', error)
      // 区分网络错误和服务器错误
      if (error.response) {
        // 服务器返回错误，优先显示服务端返回的msg
        const errorMsg = error.response.data?.msg || error.response.data?.message || '添加跟进失败'
        ElMessage.error(errorMsg)
      } else if (error.request) {
        // 请求发出但无响应
        ElMessage.error('网络连接失败，请检查网络')
      } else {
        // 其他错误
        ElMessage.error('添加跟进失败，请稍后重试')
      }
    }
  }).catch(() => {})
}

onMounted(() => {
  fetchList()
})
</script>

<style scoped lang="scss">
.resource-pool-container {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .left-actions {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .right-actions {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .filter-bar {
    display: flex;
    gap: 12px;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 10px;
  }

  .name-cell {
    display: flex;
    align-items: center;
    .name-and-id {
      display: flex;
      flex-direction: column;
      .name-text { font-weight: 600; }
      .id-text { font-size: 12px; color: #909399; }
    }
  }

  .tags-cell {
    display: flex;
    gap: 6px;
    flex-wrap: wrap;
    .tag-item { margin: 0; }
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
    padding: 16px 0 4px;
  }
  
  /* 上传对话框样式 */
  .upload-dialog-content {
    .upload-tip {
      margin-bottom: 16px;
      color: #606266;
    }
    
    .upload-btn {
      display: flex;
      justify-content: center;
      margin-bottom: 16px;
    }
    
    .progress-text {
      text-align: center;
      margin-top: 8px;
      color: #606266;
    }
  }
  
  /* 客户详情抽屉样式优化 */
  .customer-detail-drawer {
    .el-drawer__header {
      padding: 16px 20px 12px;
      border-bottom: 1px solid #ebeef5;
      .el-drawer__title {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
      }
    }
  }
  
  .customer-detail {
    padding: 20px;
    animation: fadeIn 0.3s ease-in-out;
  }
  
  /* 客户头部信息 */
  .info-header {
    background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
    padding: 24px;
    border-radius: 8px;
    color: white;
    text-align: center;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
  }
  
  .customer-name {
    font-size: 22px;
    font-weight: 600;
    margin-bottom: 10px;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  }
  
  .customer-phone {
    font-size: 16px;
    opacity: 0.95;
  }
  
  /* 间距工具类 */
  .mt-4 {
    margin-top: 20px;
  }
  
  /* 详情列表样式 */
  .customer-detail .el-descriptions {
    background-color: #ffffff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    border: 1px solid #ebeef5;
  }
  
  /* 详情项样式 */
  .customer-detail .el-descriptions-item {
    border-bottom: 1px solid #ebeef5;
    transition: background-color 0.2s ease;
  }
  
  .customer-detail .el-descriptions-item:last-child {
    border-bottom: none;
  }
  
  .customer-detail .el-descriptions__label {
    background-color: #f4f4f5;
    font-weight: 500;
    color: #606266;
    padding: 12px 16px !important;
    border-right: 1px solid #ebeef5;
    min-width: 110px;
    font-size: 13px;
  }
  
  .customer-detail .el-descriptions__content {
    padding: 12px 16px !important;
    color: #303133;
    font-size: 13px;
    line-height: 1.5;
  }
  
  /* 客户情况描述样式 */
  .situation-content {
    padding: 10px;
    background-color: #f0f9ff;
    border-radius: 4px;
    border-left: 3px solid #409eff;
    line-height: 1.6;
    font-size: 13px;
    word-break: break-word;
    white-space: pre-wrap;
  }
  
  /* 标签样式优化 */
  .customer-detail .tag-item {
    margin: 2px 6px 2px 0;
    padding: 2px 10px;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 500;
    transition: all 0.2s ease;
  }
  
  /* 编辑对话框中的标签样式 */
  .tag-input-container {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    padding: 5px 0;
  }
  
  .tag-input {
    width: 140px;
    margin-left: 8px;
  }
  
  .tag-input-container .tag-item {
    margin: 2px 4px;
  }
  
  /* 操作按钮区域样式 */
  .detail-actions {
    margin-top: 20px;
    padding-top: 16px;
    border-top: 1px solid #ebeef5;
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
  }
  
  .detail-actions .el-button {
    padding: 8px 16px;
    font-size: 13px;
    border-radius: 4px;
    transition: all 0.2s ease;
  }
  
  .detail-actions .el-button:hover {
    box-shadow: 0 2px 6px rgba(64, 158, 255, 0.2);
  }
  
  /* 动画效果 */
  @keyframes fadeIn {
    from {
      opacity: 0;
      transform: translateY(10px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
}
</style>